import tornado
import tornado.web
from tornado.websocket import WebSocketHandler
from db import db
from util.myredis import r
import time
conndict={}
class WebsocketHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True

    # 建立连接
    def open(self):
        # 获取参数
        id = int(self.get_query_argument("id"))
        # 存储链接
        conndict[id] = self

    # 接收消息
    def on_message(self, mes):
        self.write_message(mes)
        print(mes)

    def on_close(self):
        pass
class TTHandler(tornado.web.RequestHandler):
    def get(self):
        msg = self.get_query_argument("mes")
        id = int(self.get_query_argument("id"))
        conndict[id].write_message(msg)
import json
class Greenhouse(tornado.web.RequestHandler):
    def get(self):
        id = int(self.get_query_argument('id'))
        while True:
            web = r.get_str('key')
            print(web)
            if web:
                key = int(web.decode())
                sql = "select * from webs"
                res = db.findAll(sql)
                print(res)
                list = []
                for i in res:
                    if i['min'] <= key <= i['max']:
                        status = 1
                        list.append(
                            {'id': i['id'], 'name': i['name'], 'min': i['min'], 'max': i['max'], 'status': status,
                             'key': key})
                    else:
                        status = 0
                        list.append(
                            {'id': i['id'], 'name': i['name'], 'min': i['min'], 'max': i['max'], 'status': status,
                             'key': key})
                time.sleep(3)
                conndict[id].write_message(json.dumps(list))